/*
 * @name: 新建抽奖商品
 * @Author: along
 * @Date: 2020-06-09
 */
<template>
    <div class="container zdLuckCreate">
        <div class="page">
            <div class="container-wrap">
                <p class="container-wrap-line"/>
                <p class="container-wrap-title">添加抽奖商品</p>
            </div>
            <div class="wrap">
                <el-form
                    :model="ruleForm"
                    :rules="rules"
                    :label-position="'left'"
                    ref="ruleForm"
                    label-width="120px"
                    class="demo-ruleForm"
                >
                    <el-form-item
                        label="选择自营商品"
                    >
                        <el-button
                            size="small"
                            type="primary"
                            @click="fnShowDialog()"
                        >
                            选择商品
                        </el-button>
                    </el-form-item>
                    <el-form-item
                        label="缩略图"
                        v-if="ruleForm.goods_cover"
                    >
                        <img
                            :src="ruleForm.goods_cover"
                            alt="加载失败"
                            style="width:80px;height:80px"
                            @click="fnShowPreview(ruleForm.goods_cover)"
                        >
                    </el-form-item>
                    <el-form-item
                        label="商品规格"
                        v-if="goods_product_list && goods_product_list.length > 0"
                    >
                        <el-checkbox-group
                            v-model="goods_product_list_index"
                            @change="fnGetSpeclist()"
                        >
                            <el-checkbox
                                v-for="(option,key) in goods_product_list"
                                :label="option.product_no"
                                :key="key"
                                :checked="option.lottery_status == 1 ? true : false"
                            >
                                <div class="zd-spec">
                                    <p
                                        v-for="(item,i) in option.spec_list"
                                        :key="i"
                                        class="zd-spec-text"
                                    >
                                        {{ item.spec_name + ':' + item.spec_value }}
                                    </p>
                                    <p
                                        class="zd-spec-text"
                                        v-if="option.product_price"
                                    >
                                        原价：{{ option.product_price }}
                                    </p>
                                    <p
                                        class="zd-spec-text"
                                        v-if="option.product_stock"
                                    >
                                        库存：{{ option.product_stock }}
                                    </p>
                                </div>
                            </el-checkbox>
                        </el-checkbox-group>
                    </el-form-item>
                    <el-form-item
                        label="商品名称"
                        v-if="ruleForm.shop_name"
                    >
                        {{ ruleForm.shop_name }}
                    </el-form-item>
                    <el-form-item
                        label="商品标题"
                        prop="goods_title"
                    >
                        <el-input
                            v-model="ruleForm.goods_title"
                            placeholder="请输入商品标题"
                            size="small"
                            :style="{width: '380px'}"
                            maxlength="40"
                            clearable
                        />
                    </el-form-item>
                    <!-- <el-form-item
                        label="抽奖价格"
                        prop="luck_price"
                    >
                        <div class="wrap-list">
                            <el-input
                                v-model="ruleForm.luck_price"
                                placeholder="请输入抽奖价格"
                                size="small"
                                clearable
                                :style="{width: '380px'}"
                            />
                        </div>
                    </el-form-item> -->
                    <el-form-item
                        label="抽奖价格"
                        v-if="ruleForm.lottery_price_list.length > 0"
                    >
                        <div
                            v-for="(option,index) in ruleForm.lottery_price_list"
                            :key="index"
                            style="display:flex"
                        >
                            <div
                                v-if="option.lottery_status == 1 ? true : false"
                                style="display:flex"
                            >
                                <div class="zd-spec-luck">
                                    <p
                                        v-for="(item,i) in option.spec_list"
                                        :key="i"
                                        class="zd-spec-luck-text"
                                    >
                                        {{ item.spec_name + ':' + item.spec_value }}
                                    </p>
                                </div>
                                <el-input
                                    v-model="option.lottery_price"
                                    placeholder="请输入抽奖价格"
                                    size="small"
                                    clearable
                                    :style="{width: '380px'}"
                                />
                            </div>
                        </div>
                    </el-form-item>
                    <el-form-item
                        label="原售价"
                    >
                        <div class="wrap-list">
                            <el-input
                                v-model="ruleForm.goods_price"
                                size="small"
                                clearable
                                :style="{width: '380px'}"
                                :disabled="true"
                            />
                        </div>
                    </el-form-item>
                    <el-form-item
                        label="中奖名额"
                        prop="luck_number"
                    >
                        <div class="wrap-list">
                            <el-input
                                v-model="ruleForm.luck_number"
                                placeholder="请输入中奖名额"
                                size="small"
                                clearable
                                :style="{width: '380px'}"
                            />
                        </div>
                    </el-form-item>
                    <!-- <el-form-item
                        label="商品库存"
                    >
                        <div class="wrap-list">
                            <el-input
                                v-model="ruleForm.stock"
                                size="small"
                                clearable
                                :style="{width: '380px'}"
                                :disabled="true"
                            />
                        </div>
                    </el-form-item> -->
                    <el-form-item
                        label="开奖时间"
                        prop="luck_time"
                    >
                        <div class="wrap-list">
                            <el-date-picker
                                v-model="ruleForm.luck_time"
                                type="datetime"
                                placeholder="请选择开奖日期"
                                align="right"
                                size="small"
                                :picker-options="fnGetPickerOptions()"
                                :style="{width: '380px'}"
                            />
                        </div>
                    </el-form-item>
                    <el-form-item
                        label="选择可抽奖等级"
                        prop="luck_leavel"
                    >
                        <el-select
                            v-model="ruleForm.luck_leavel"
                            clearable
                            filterable
                            placeholder="请选择"
                            size="small"
                            :style="{width: '380px'}"
                        >
                            <el-option
                                v-for="item in leavelData"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-select>
                    </el-form-item>
                    <el-form-item
                        label="排序号"
                        prop="luck_sort"
                    >
                        <el-input
                            v-model="ruleForm.luck_sort"
                            placeholder="请输入排序号"
                            size="small"
                            clearable
                            :style="{width: '380px'}"
                        />
                    </el-form-item>
                    <el-form-item
                        label="活动状态"
                        prop="luck_status"
                    >
                        <el-switch
                            v-model="ruleForm.luck_status"
                            active-text="上架"
                            inactive-text="下架"
                            :active-value="1"
                            :inactive-value="0"
                        />
                    </el-form-item>
                    <el-form-item
                        label="状态"
                        prop="lottery_scope"
                    >
                        <el-switch
                            v-model="ruleForm.lottery_scope"
                            active-text="公开"
                            inactive-text="私有"
                            :active-value="1"
                            :inactive-value="0"
                        />
                    </el-form-item>
                    <el-form-item
                    >
                        <el-button
                            size="small"
                            type="primary"
                            @click="fnSubmit('ruleForm')"
                            style="width:80px"
                        >
                            提交
                        </el-button>
                        <el-button
                            size="small"
                            type="info"
                            style="margin-left: 50px"
                            @click="()=> {
                                this.$router.push({
                                    name: 'zdLuckDraw'
                                })
                            }"
                        >
                            返回列表
                        </el-button>
                    </el-form-item>
                </el-form>
            </div>
        </div>

        <!-- 添加自营商品弹窗 -->
        <create-shop
            ref="createShop"
            @changeData="getData"
        />

        <!-- 图片预览 -->
        <img-preview ref="preview" />
    </div>
</template>

<script>
import { back } from '@/mixin/back';
import createShop from '@/components/student/luck/create-shop';
import imgPreview from '@/components/common/img-preview';
export default {
    mixins: [back],
    components: {
        createShop,
        imgPreview
    },
    data () {
        const validatePrice = (rule, value, callback) => {
            if(Number(value) == 0) {
                callback(new Error('抽奖价格不能为0'));
            }else if (Number(value) > Number(this.ruleForm.goods_price)) {
                callback(new Error('抽奖价格不能大于售价'));
            } else {
                callback();
            }
        };

        const validateNumber = (rule, value, callback) => {
            if (Number(value) > Number(this.ruleForm.stock)) {
                callback(new Error('中奖名额不能大于库存'));
            } else {
                callback();
            }
        };

        const validateTime = (rule, value, callback) => {
            let now_time = new Date().getTime();
            let luck_time = new Date(value).getTime();

            if (luck_time <= now_time) {
                callback(new Error('开奖时间应大于当前时间'));
            } else {
                callback();
            }
        };

        return {
            goods_product_list: [],//商品规格数据
            goods_product_list_index: [],//选中的数据位置
            goods_product_list_acyive: [],//填写数据
            type: '',
            ruleForm: {
                goods_title: '',
                // luck_price: '',
                lottery_price_list: [],
                goods_price: '',
                luck_number: '',
                // stock: '',
                luck_time: '',
                luck_leavel: '',
                luck_sort: '',
                luck_status: 1,
                goods_cover: '',
                shop_name: '',
                lottery_scope: 1
            },
            rules: {
                goods_title: [
                    { required: true, message: '请填写商品标题', trigger: 'change' }
                ],
                luck_price: [
                    { validator: validatePrice, trigger: 'change' },
                    { required: true, message: '请填写抽奖价格', trigger: 'change' }
                ],
                luck_number: [
                    { validator: validateNumber, trigger: 'change' },
                    { required: true, message: '请填写中奖名额', trigger: 'change' }
                ],
                luck_time: [
                    { validator: validateTime, trigger: 'change' },
                    { required: true, message: '请填写开奖时间', trigger: 'change' }
                ],
                luck_leavel: [
                    { required: true, message: '请选择可抽奖等级', trigger: 'change' }
                ],
                luck_sort: [
                    { required: true, message: '请填写排序号', trigger: 'change' }
                ]
            },
            leavelData: [{
                value: -1,
                label: '所有用户'
            },{
                value: 0,
                label: 'E0'
            },{
                value: 1,
                label: 'E1'
            },{
                value: 2,
                label: 'E2'
            },{
                value: 3,
                label: 'E3'
            },{
                value: 4,
                label: 'E4'
            },{
                value: 5,
                label: 'E5'
            }],
            authResult: {},
            lottery_no: '',
            goods_no: ''
        };
    },
    filters: {},
    computed: {},
    watch: {},
    created () {
    },
    mounted () {
        this.$store.commit('SET_HEADER', [{ title: "APP后台"},{title: '商城'},{title: '抽奖商品管理'},{title: '添加抽奖商品'}]);
        this.authResult = this.$route.meta.authResult;

        let query = this.$route.query;

        if(query.lottery_no) {
            this.lottery_no = query.lottery_no;
            this.fnGetData();
        }

        if(query.type) {
            this.type = query.type;
        }
    },
    methods: {
        /**
         * 获取商品抽奖数据
         */
        fnGetData () {
            this.$post('/student/shop_lottery%5Cget',{
                lottery_no: this.lottery_no
            },resp => {
                if(resp.code == 1) {
                    this.goods_no = resp.data.goods_no;
                    this.ruleForm.goods_cover = resp.data.goods_cover;
                    this.ruleForm.shop_name = resp.data.goods_title;
                    this.ruleForm.goods_title = resp.data.lottery_title;
                    // this.ruleForm.luck_price = resp.data.lottery_price;
                    this.ruleForm.luck_number = resp.data.lottery_num;
                    this.ruleForm.luck_time = resp.data.lottery_time * 1000;
                    this.ruleForm.luck_leavel = resp.data.lottery_level;
                    this.ruleForm.luck_sort = resp.data.lottery_sort;
                    this.ruleForm.luck_status = resp.data.lottery_show;
                    // this.ruleForm.stock = resp.data.goods_stock;
                    this.ruleForm.goods_price = resp.data.goods_price;
                    this.goods_product_list = resp.data.lottery_product_list;
                    this.ruleForm.lottery_price_list = resp.data.lottery_product_list;

                    this.ruleForm.lottery_scope = resp.data.lottery_scope == 'public' ? 1 : 0;
                } else {
                    this.$message({
                        type: 'warning',
                        message: resp.msg
                    });
                }
            });
        },

        /**
         * 提交数据
         */
        fnSubmit (formName) {

            if(this.type == 'add') {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        this.$post('/student/shop_lottery%5Cadd',{
                            goods_no: this.goods_no,
                            lottery_title: this.ruleForm.goods_title,
                            // lottery_price: this.ruleForm.luck_price,
                            lottery_num: this.ruleForm.luck_number,
                            lottery_time: this.ruleForm.luck_time == '' || this.ruleForm.luck_time === null ? '' : new Date(this.ruleForm.luck_time).getTime() / 1000,
                            lottery_level: this.ruleForm.luck_leavel,
                            lottery_sort: this.ruleForm.luck_sort,
                            lottery_show: this.ruleForm.luck_status,
                            lottery_product_json: JSON.stringify(this.ruleForm.lottery_price_list),
                            lottery_scope: this.ruleForm.lottery_scope == 1 ? 'public' : 'private'
                        },resp => {
                            if(resp.code == 1) {
                                this.$message({
                                    type: 'success',
                                    message: '添加成功'
                                });
                                setTimeout(() => {
                                    this.$router.push({
                                        name: 'zdLuckDraw'
                                    });
                                }, 200);
                            } else {
                                this.$message({
                                    type: 'warning',
                                    message: resp.msg
                                });
                            }
                        });
                    } else {
                        console.log('error submit!!');
                        return false;
                    }
                });
            } else if(this.type == 'edit') {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        this.$post('/student/shop_lottery%5Cupdate',{
                            lottery_no: this.lottery_no,
                            goods_no: this.goods_no,
                            lottery_title: this.ruleForm.goods_title,
                            // lottery_price: this.ruleForm.luck_price,
                            lottery_num: this.ruleForm.luck_number,
                            lottery_time: this.ruleForm.luck_time == '' || this.ruleForm.luck_time === null ? '' : new Date(this.ruleForm.luck_time).getTime() / 1000,
                            lottery_level: this.ruleForm.luck_leavel,
                            lottery_sort: this.ruleForm.luck_sort,
                            lottery_show: this.ruleForm.luck_status,
                            lottery_product_json: JSON.stringify(this.ruleForm.lottery_price_list),
                            lottery_scope: this.ruleForm.lottery_scope == 1 ? 'public' : 'private'
                        },resp => {
                            if(resp.code == 1) {
                                this.$message({
                                    type: 'success',
                                    message: '修改成功'
                                });
                                setTimeout(() => {
                                    this.$router.push({
                                        name: 'zdLuckDraw'
                                    });
                                }, 200);
                            } else {
                                this.$message({
                                    type: 'warning',
                                    message: resp.msg
                                });
                            }
                        });
                    } else {
                        console.log('error submit!!');
                        return false;
                    }
                });
            } else {
                this.$message({
                    type: 'warning',
                    message: '类型错误'
                });
                setTimeout(() => {
                    this.$router.push({
                        name: 'zdLuckDraw'
                    });
                }, 200);
            }
        },

        /**
         * 打开自营商品弹窗
         */
        fnShowDialog () {
            this.$refs.createShop.showDialog();
        },

        /**
         * 获取弹窗选中数据
         */
        getData (res) {
            console.log(res);
            if(res) {
                this.ruleForm.goods_title = this.ruleForm.shop_name = res.goods_title;
                this.ruleForm.goods_price = res.goods_price;
                this.ruleForm.goods_cover = res.goods_cover;
                // this.ruleForm.stock = res.goods_stock;
                this.goods_no = res.goods_no;

                this.$post('/student/shop_lottery%5Cget_lottery_product_list', {
                    goods_no: this.goods_no
                }, resp => {
                    if(resp.code == 1) {
                        this.ruleForm.lottery_price_list = resp.data;
                        this.goods_product_list = resp.data;
                    } else {
                        this.$message({
                            type: 'warning',
                            message: resp.msg
                        });
                    }
                });
            }
        },

        /**
         * 获取选中的规格数据
         * 主要在于取消选择/增加选择/清空时/填充已填写价格
         */
        fnGetSpeclist () {
            let list = [];
            let checkData = [];

            this.goods_product_list.find(item => {
                if(this.goods_product_list_index.includes(item.product_no)) {
                    item.lottery_status = 1;
                    checkData.push(item);
                } else {
                    item.lottery_price = item.lottery_status = 0;
                    checkData.push(item);
                }
            });

            this.ruleForm.lottery_price_list = checkData;

            console.log(this.ruleForm.lottery_price_list, 'aa');
        },

        /**
         * 查看图片
         * @param   {String}    images      //单图预览
         * @param   {Array}     images      //多图预览
         */
        fnShowPreview(images) {
            if(images && Object.prototype.toString.call(images) == '[object String]') {
                this.$refs.preview.show([
                    images
                ]);
            } else if (images && Object.prototype.toString.call(images) == '[object Array]') {
                this.$refs.preview.show(images);
            } else {
                this.$message({
                    type: 'warning',
                    message: '图片类型错误'
                });
            }
        },

        /**
         * 默认时间加载
         */
        fnGetPickerOptions () {

            return {
                shortcuts : [{
                    text: '昨天',
                    onClick(picker) {
                        const date = new Date();

                        date.setTime(date.getTime() - 3600 * 1000 * 24);
                        picker.$emit('pick', date);
                    }
                },{
                    text: '今天',
                    onClick(picker) {
                        picker.$emit('pick', new Date());
                    }
                },{
                    text: '明天',
                    onClick(picker) {
                        const date = new Date();

                        date.setTime(date.getTime() + 3600 * 1000 * 24);
                        picker.$emit('pick', date);
                    }
                },{
                    text: '后天',
                    onClick(picker) {
                        const date = new Date();

                        date.setTime(date.getTime() + 3600 * 1000 * 24 * 2);
                        picker.$emit('pick', date);
                    }
                }]
            };
        },
    }
};
</script>

<style lang="less" scoped>
.container {
    background-color: #fff;
    display: flex;
    flex-direction: column;
    position: relative;
    width: 100%;
    max-height: 100vh;
    .page {
        background-color: #fff;
        padding: 10px 15px 5px 15px;
        background-color: #fff;
    }
    &-wrap {
        height: 20px;
        display: flex;
        align-items: center;
        &-line {
            width: 3px;
            height: 20px;
            background: #1890ff;
            margin-right: 5px;
        }
        &-title {
            font-size: 16px;
            color: #333;
            font-weight: 500;
        }
    }
    .wrap {
        width: 100%;
        display: flex;
        flex-direction: column;
        padding: 30px;
        // border: 1px red solid;
    }
    .wrap-list {
        height: 32px;
        display: flex;
        align-items: center;
        &-text {
            margin-left: 15px;
            font-size: 14px;
            color: #333;
        }
    }
    .zd-spec-luck {
        display: flex;
        color: #606266;
        font-size: 14px;
        &-text {
            margin-right: 10px;
        }
    }
}
</style>
<style lang="less">
    .zdLuckCreate{
        .el-form-item {
            margin-bottom: 20px;
        }
        .el-checkbox-group {
            display: flex;
            flex-direction: column;
            .zd-spec {
                display: flex;
                width: 1009px;
                overflow: hidden;
                white-space: nowrap;
                text-overflow: ellipsis;
                .zd-spec-text {
                    font-size: 14px;
                    margin-right: 10px;
                }
            }
        }
    }
</style>
